package com.example.fairplay.newfpregistration.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fairplay.newfpregistration.R;
import com.example.fairplay.newfpregistration.adapter.RecordDatasAdapter;
import com.example.fairplay.newfpregistration.util.StatusBarCompat;
import com.example.mylibrary.CallBack;
import com.example.mylibrary.data.ByteImg;
import com.example.mylibrary.data.DBManager;
import com.example.mylibrary.data.DataDao;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.util.ExlUtils;
import com.example.mylibrary.util.ExportExcelUtli;
import com.example.mylibrary.util.GreenDaoManager;
import com.example.mylibrary.util.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.aratek.facelib.AraFaceAuthLib;


public class RecordItemActivity2 extends Activity implements AdapterView.OnItemSelectedListener, PopupMenu.OnMenuItemClickListener {

	@Bind(R.id.rv_InfoItemview)
	RecyclerView recyclerView;
	@Bind(R.id.tv_tips)
	TextView tv_tips;
	@Bind(R.id.spinner_sex)
	Spinner spinnerSex;
	@Bind(R.id.spinner_rollcall_status)
	Spinner spinnerRollcallStatus;
	@Bind(R.id.spinner_send_status)
	Spinner spinnerSendStatus;
	@Bind(R.id.ed_select)
	EditText stuCodeOrCrad;

	@Bind(R.id.text_title)
	TextView tvTitle;
	@Bind(R.id.button_backward)
	Button btnBack;
	@Bind(R.id.btn_more)
	Button btnMore;

	private Context mContext;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
					ToastUtils.Toast(mContext, mString);
					mProgressDialog.dismiss();
					studentInfos.clear();
					studentInfos.addAll(DBManager.getInstance(mContext).loadAllStudents());
					myAdapter.notifyDataSetChanged();
					tv_tips.setText("共" + studentInfos.size() + "条");
					break;
				default:
					break;
			}
		}
	};
	private AraFaceAuthLib araFaceAuthLib;
	public static final int EXEL_READ_SUCCESS = 0X0;
	public static final int EXEL_READ_FAIL = 0X1;
	private String mString;
	private List<StudentInfo> studentInfos;
	private RecordDatasAdapter myAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_record_item);
		StatusBarCompat.compat(this, Color.rgb(7, 136, 242));
		ButterKnife.bind(this);
		mContext = this;
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initEvent();
		initDatas();
		//回调结果
		ExlUtils.getInstance().setExlListener(new ExlUtils.ExlListener() {
			@Override
			public void onExlResponse(final int responseCode) {
				Log.e("mProgressDialog: ", responseCode + " 0");
				switch (responseCode) {
					case EXEL_READ_SUCCESS:
						mString = "导入数据成功";
						mHandler.sendEmptyMessage(0);
						break;
					case EXEL_READ_FAIL:
						mString = "导入数据失败";
						mHandler.sendEmptyMessage(0);
						break;
				}
			}
		});
	}

	private void initDatas() {
		studentInfos = DBManager.getInstance(mContext).loadAllStudents();
		myAdapter = new RecordDatasAdapter(mContext, studentInfos);
		recyclerView.setAdapter(myAdapter);
		Log.i("studentInfos-->", studentInfos.toString());
	}

	@OnClick({R.id.export, R.id.button_backward, R.id.btn_more})
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.button_backward:
				finish();
				break;
			case R.id.btn_more:
				//创建弹出式菜单对象（最低版本11）
				PopupMenu popup = new PopupMenu(this, v);//第二个参数是绑定的那个view
				//获取菜单填充器
				MenuInflater inflater = popup.getMenuInflater();
				//填充菜单
				inflater.inflate(R.menu.menu_seting_actionbar, popup.getMenu());
				//绑定菜单项的点击事件
				popup.setOnMenuItemClickListener(this);
				//显示
				popup.show();
				break;
			case R.id.export:

				break;
			default:
				break;
		}
	}

	private void initEvent() {
		//默认为垂直
		recyclerView.setLayoutManager(new LinearLayoutManager(this));
		recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setCancelable(false);
		araFaceAuthLib = MainMenu.getAraFaceAuthLib();

		tvTitle.setText("数据管理");
		btnMore.setVisibility(View.VISIBLE);

		spinnerRollcallStatus.setOnItemSelectedListener(this);
		spinnerSendStatus.setOnItemSelectedListener(this);
		spinnerSex.setOnItemSelectedListener(this);

	}


	private int sexFlag = 9999;
	private int recordFlag = 9999;
	private int sendFlag = 9999;

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		switch (parent.getId()) {
			case R.id.spinner_sex:
				switch (position) {
					case 0://所有
						sexFlag = 9999;
						break;
					case 1://男
						sexFlag = 0;
						break;
					case 2://女
						sexFlag = 1;
						break;
					default:
						break;
				}
				studentInfos.clear();
				studentInfos.addAll(DBManager.getInstance(mContext).queryStuInfosForSpinner(sexFlag, recordFlag, sendFlag));
				myAdapter.notifyDataSetChanged();
				tv_tips.setText("共" + studentInfos.size() + "条");
				break;
			case R.id.spinner_rollcall_status:
				switch (position) {
					case 0://所有
						recordFlag = 9999;
						break;
					case 1://未检录
						recordFlag = 0;
						break;
					case 2://通过
						recordFlag = 1;
						break;
					case 3://未通过
						recordFlag = -1;
						break;
					default:
						break;
				}
				studentInfos.clear();
				studentInfos.addAll(DBManager.getInstance(mContext).queryStuInfosForSpinner(sexFlag, recordFlag, sendFlag));
				myAdapter.notifyDataSetChanged();
				tv_tips.setText("共" + studentInfos.size() + "条");
				break;
			case R.id.spinner_send_status:
				switch (position) {
					case 0://所有
						sendFlag = 9999;
						break;
					case 1://未发送
						sendFlag = 0;
						break;
					case 2://已发送
						sendFlag = 1;
						break;
					default:
						break;
				}
				studentInfos.clear();
				studentInfos.addAll(DBManager.getInstance(mContext).queryStuInfosForSpinner(sexFlag, recordFlag, sendFlag));
				myAdapter.notifyDataSetChanged();
				tv_tips.setText("共" + studentInfos.size() + "条");
				break;
			default:
				break;
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	public static final String FILE_IMG = "/sdcard/FP-KTA2203/img/";
	private ProgressDialog mProgressDialog;

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.btn_downLoad:

				break;
			case R.id.btn_delALL:
				mProgressDialog.setTitle(getString(R.string.loading));
				mProgressDialog.setMessage(getString(R.string.preparing_device));
				mProgressDialog.show();
				GreenDaoManager greenDaoManager = new GreenDaoManager(this);
				greenDaoManager.deleSQL();
				mProgressDialog.dismiss();
				break;
			case R.id.btn_insertImg:
				mProgressDialog.setTitle(getString(R.string.loading));
				mProgressDialog.setMessage(getString(R.string.preparing_device));
				mProgressDialog.show();

				new Thread() {
					@Override
					public void run() {
						super.run();
						final List<String> list = new ArrayList();
						//循环此目录下所有图片
						File scanner5Directory = new File(FILE_IMG);
						if (scanner5Directory.isDirectory()) {
							for (File file : scanner5Directory.listFiles()) {
								String path = file.getAbsolutePath();
								if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")) {
									list.add(path);
								}
							}
						}

						if (list.size() < 1) {
							mProgressDialog.dismiss();
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									Toast.makeText(mContext, "此路径下无照片", Toast.LENGTH_SHORT).show();
								}
							});
						}
						int j = 0;
						for (final String sFile : list) {

							j++;
							ByteArrayOutputStream baos = new ByteArrayOutputStream();
							Bitmap bm1 = BitmapFactory.decodeFile(sFile);
							String s = sFile;
							//去除多余路径保留图片名称
							String temp[] = s.replaceAll("\\\\", "/").split("/");
							String fileName = "";
							if (temp.length > 1) {
								fileName = temp[temp.length - 1];
							}
							//去除扩展名
							String prefix = fileName.substring(0, fileName.lastIndexOf("."));

							Log.e("path: ", prefix + "");

							Log.e("BitmapTime------->", bm1 + "");
							//将图片转换成byte[]
							bm1.compress(Bitmap.CompressFormat.PNG, 100, baos);
							byte[] bm1Byte = baos.toByteArray();
							byte[] cardData = araFaceAuthLib.getFeature(bm1);
							Log.e("cardDataTime-------> ", cardData + "");
							ByteImg byteImg = new ByteImg();

							byteImg.setStudentCode(prefix);
							byteImg.setImgFeature(cardData);
							byteImg.setByteImg(bm1Byte);
							//将图片保存在数据库
							DataDao.insertImg(byteImg);
							if (j == list.size()) {
								Log.e("dismiss: ", j + "-----" + list.size());
								mProgressDialog.dismiss();
								break;
							}

						}
					}
				}.start();
				break;
			case R.id.btn_delInfo:
				DataDao.deleteInfo();
				studentInfos.clear();
				myAdapter.notifyDataSetChanged();
				tv_tips.setText("共" + studentInfos.size() + "条");
				break;
			case R.id.btn_readInfo:
				Intent intent = new Intent(mContext,
						FilePickActivity2.class);
				startActivityForResult(intent, 0);
				break;
			case R.id.btn_exportInfo:
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						new ExportExcelUtli(studentInfos);
						Toast.makeText(mContext, "已导出到本地文件夹", Toast.LENGTH_SHORT).show();
					}
				});
				break;
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 0) {
			final String filePath = data.getStringExtra("filePath");
			if (null != filePath && filePath.length() > 0) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mProgressDialog.setTitle(getString(R.string.loading));
						mProgressDialog.setMessage(getString(R.string.preparing_device));
						mProgressDialog.show();

						ExlUtils.getInstance().readExlData3(mContext, filePath, new CallBack() {
							@Override
							public void onSucess(Object o) {
							}

							@Override
							public void onFail(String string) {
							}
						});

					}
				});
			} else {
				Toast.makeText(mContext, "未选择文件",
						Toast.LENGTH_SHORT).show();
			}
		}
	}
}
